
var Event = YAHOO.util.Event, 
	Button = YAHOO.widget.Button,
	Connect = YAHOO.util.Connect, 
	UA = YAHOO.env.ua, 
	JSON = YAHOO.lang.JSON,
	DataSource = YAHOO.util.DataSource,
	DataTable = YAHOO.widget.DataTable,
	Panel = YAHOO.widget.Panel;
	Dialog = YAHOO.widget.Dialog;
	Cookie = YAHOO.util.Cookie;


var promotion=new Object;		//营销活动全局变量
var areas=['全部','东区', '西区', '南区', '北区', '中心区']			//区域
var custType=['全部', 'A类', 'B类', 'C类'];


/**
 * 简化document.getElementById的写法
 * @param {} tagId
 * @return {}
 */
var element = function(tagId) {
	return document.getElementById(tagId);
}



/**                            
* 方法:Array.Contains(obj)     
* 功能:确定某个元素是否在数组中.        
* 参数:要查找的Object对象 
* 返回:找到返回true,否则返回false; 
*/                                                
Array.prototype.contains=function(obj) 
{ 
   for(var i=0;i<this.length;i++) 
   { 
    if(this[i]==obj) 
    { 
     return true; 
    } 
   } 
   return false; 
} 

var checkboxHtml=function(label, id, name, checked){
	if (checked) {
		return '<input type="checkbox" id="'+id+'" name="'+name+'" checked="checked" /><label for="'+id+'">'+label+'</label>';
	} else {
		return '<input type="checkbox" id="'+id+'" name="'+name+'" /><label for="'+id+'">'+label+'</label>';		
	}
}

// ===============yui导航按钮==============================
Event.onContentReady('navButton', function() {
	var oButtonGroup = new YAHOO.widget.ButtonGroup('buttongroup', {
	});
});

Event.onContentReady('navButton', function() {
	Event.addListener('radio1', 'click', showPromotionList);
});


/**
 * 对话框按钮
 * @type 
 */
var submitButton={text:"添加", handler:function(){this.submit()}, isDefault:true};
var cancelButton={text:"取消", handler:function(){this.cancel()}};



//==================目标客户=================================

var promotionCustSection=element('promotionCust');						//显示目标客户的区域--span
var promotionCustFormDiv=element('promotionCustFormDiv');				//目标客户编辑区域，平时隐藏
var promotionCustAreaFieldset=element('promotionCustAreaFieldset');		//客户区域和类型的表单
var promotionCustTypeFieldset=element('promotionCustTypeFieldset');		//客户区域和类型的表单
var promotionCustFileFieldset=element('promotionCustFileFieldset');		//客户区域和类型的表单

var onPromotionCustSubmitButtonClick=function(){
	promotionCustFormDiv.style.display='none';
};
var onPromotionCustCancelButtonClick=function(){
	promotionCustFormDiv.style.display='none';
};

var onPromotionCustFileSubmitButtonClick=function(){
	promotionCustFormDiv.style.display='none';
};
var onPromotionCustFileCancelButtonClick=function(){
	promotionCustFormDiv.style.display='none';
};

var onPromotionCustSuccess=function(o){
	var list=JSON.parse(o.responseText);
	promotion.custList=list;
	
	var custHtml='';
	if(list.area.toString()=='全部'&&list.type.toString=='全部'){
		custHtml='全部客户';
	} else {
		custHtml=list.area.toString()+list.type.toString()+'客户';
	};
	custHtml=custHtml+'&nbsp;&nbsp;&nbsp;&nbsp;';
	if (list.file!=null) {
		custHtml=custHtml+'附加:';
		for (var i = 0, len = list.file.length; i < len; ++i) {
			var tmp=[];
			tmp[0]='<a href="/promotion/';
			tmp[1]=promotion.id;
			tmp[2]='/custFile/';
			tmp[3]=list.file[i];
			tmp[4]='">';
			tmp[5]=list.file[i];
			tmp[6]='</a>&nbsp;&nbsp;&nbsp;'
			custHtml=custHtml+tmp.join('');
		};
	};
	
	promotionCustSection.innerHTML=custHtml;
	
	var formHtml='<legend>选择区域</legend>';
	for (var i = 0, len = areas.length; i < len; ++i) {
		formHtml=formHtml+checkboxHtml(areas[i], 'promotionArea'+i, 'area', list.area.contains(areas[i]));
	};
	promotionCustAreaFieldset.innerHTML=formHtml;
	
	formHtml='<legend>选择类型</legend>';
	for (var i = 0, len = custType.length; i < len; ++i) {
		formHtml=formHtml+checkboxHtml(custType[i], 'promotionCustType'+i, 'custType', list.type.contains(custType[i]));
	};
	promotionCustTypeFieldset.innerHTML=formHtml;	
	
	formHtml='<legend>附加客户清单</legend>';
	for (var i = 0, len = list.file.length; i < len; ++i) {
		formHtml=formHtml+list.file[i];
		formHtml=formHtml+'<a href="#" onclick="javascript:onDeletePromotionCustFileClick(\''+list.file[i]+'\')">删除</a>';
		formHtml=formHtml+'<br />';
	};
	promotionCustFileFieldset.innerHTML=formHtml;
	
	Event.on('promotionCustSubmitButton', 'click', onPromotionCustSubmitButtonClick);
	Event.on('promotionCustCancelButton', 'click', onPromotionCustCancelButtonClick);

	Event.on('promotionCustFileSubmitButton', 'click', onPromotionCustFileSubmitButtonClick);
	Event.on('promotionCustFileCancelButton', 'click', onPromotionCustFileCancelButtonClick);

};

var onPromotionCustFailure=function(o){
};

var promotionCustDialog=new Dialog('promotionCustDialog', 
						{width:"400px",
						fixedcenter:true,
						modal:true,
						buttons : [submitButton, cancelButton],
						callback: {success:onPromotionCustSuccess, upload:onPromotionCustSuccess,failure:onPromotionCustFailure}
						}
);


var onPromotionCustLinkClick = function(){
	if (promotionCustFormDiv.style.display=='none') {
		promotionCustFormDiv.style.display='block';
	} else {
		promotionCustFormDiv.style.display='none';
	}
};

var requestPromotionCust=function(){
	var callback = {
		cache : false,
		success : onPromotionCustSuccess
	};
	Connect.asyncRequest('GET', '/promotion/' + promotion.id + '/custList', callback);	
};
//requestPromotionCust();

/**
 * 注册客户链接点击事件
 */
Event.on('promotionCustLink', 'click', onPromotionCustLinkClick);




//=================附件的事件、控件和其它函数，费时2天！！！===================================
var showAttachment=function() {
	var list=promotion.attachmentList;
	if (list==null) {
		element('attachment').innerHTML='(没有附件)';
		element('promotionAttachmentFieldset').innerHTML='';
		return;
	} 

	//刷新附件清单区域
	var html='';
	for (var i = 0, len = list.length; i < len; ++i) {
		html=html+'<a href="/store/upload/'+list[i]+'">'+list[i]+'</a>&nbsp;&nbsp;&nbsp;';
		}
	element('attachment').innerHTML=html;		
	
	//填充隐藏表单
	html='';
		
	for (var i = 0, len = list.length; i < len; ++i) {
		html=html+list[i];
		html=html+'&nbsp;&nbsp;&nbsp;';
		html=html+'<a href="#" onclick="javascript:onDeleteAttachmentClick(\''+list[i]+'\')">删除</a>';
		html=html+'<br />';
	};
	element('promotionAttachmentFieldset').innerHTML=html;
};

/**
 * 附件处理成功后，request、delete、upload后触发
 * @param {} o
 */
var onAttachmentSuccess=function(o){
	if (o.responseText==null || o.responseText=='') {
		promotion.attachmentList=null;
	} else {
		//更新promotion数据
		promotion.attachmentList=JSON.parse(o.responseText).attachment.file;
	}
	
	showAttachment();
};

/*
 * 
 * 
 * 处理附件提交失败
 * @param {} o
 */
var onAttachmentFailure=function(o){
	
};

/**
 * 用户在对话框中点击"删除"链接,删除指令发送后，服务器将返回新的附件清单
 * @param {} fileName
 */
var onDeleteAttachmentClick=function(fileName) {
	var callback = {
		cache : false,
		success : onAttachmentSuccess
	};
	Connect.asyncRequest('DELETE', '/promotion/' + promotion.id + '/attachment/'+fileName, callback);
	promotionAttachmentFormDiv.style.display='none';
};


/**
 * 向服务器请求文件清单
 */
var loadAttachment=function(){
	var callback = {
		cache : false,
		success : onAttachmentSuccess
	};
	Connect.asyncRequest('GET', '/promotion/' + promotion.id + '/attachment/list', callback);
};

var onAttachmentLinkClick = function(){
	if (element('promotionAttachmentFormDiv').style.display=='none') {
		element('promotionAttachmentFormDiv').style.display='block';
	} else {
		element('promotionAttachmentFormDiv').style.display='none';
	}
};

var onPromotionAttachmentSubmitButtonClick=function(){
	var callback = {
		cache : false,
		success : onAttachmentSuccess
	};
	Connect.setForm(element('promotionAttachmentForm'), true);
	Connect.asyncRequest('POST', '/promotion/' + promotion.id + '/attachment', callback);
	promotionAttachmentFormDiv.style.display='none';
};
var onPromotionAttachmentCancelButtonClick=function(){
	promotionAttachmentFormDiv.style.display='none';
};
Event.on('promotionAttachmentSubmitButton', 'click', onPromotionAttachmentSubmitButtonClick);
Event.on('promotionAttachmentCancelButton', 'click', onPromotionAttachmentCancelButtonClick);

/**
 * 注册附件链接点击事件
 */
Event.on('attachmentLink', 'click', onAttachmentLinkClick);


//====================附件操作结束===========================







//====================反馈开始=============================




/**
 * 数据表的列集
 * @type 
 */
var resultColumnDefs = [
	{key:'custName', label:'客户', sortable:true, resizeable:true},
	{key:'content', label:'反馈', sortable:true, resizeable:true},
	{key:'date', label:'日期', sortable:true, sortOptions:{defaultDir:DataTable.CLASS_DESC},resizeable:true}
];

var requestResultTable=function(o){
	var ds = new DataSource('/promotion/' + promotionId + '/resultList');
	ds.responseType = DataSource.TYPE_JSARRAY;
	ds.responseSchema = {fields: [{key:'id', parser:'number'},
	                              {key:'custName'},
	                              {key:'content'},
	                              {key:'date'}
	                              ]};
	var table=new DataTable('resultTable', resultColumnDefs, ds, {selectionMode:"single"});
    table.subscribe("rowMouseoverEvent", table.onEventHighlightRow);
    table.subscribe("rowMouseoutEvent", table.onEventUnhighlightRow);
    
    var openResultDialog=function(o) {
    	var target=o.target;
    	var record=this.getRecord(target);
    	alert(record.getData('content'));
    };
    table.subscribe("rowClickEvent", openResultDialog);	
};

//requestResultTable();		//测试


//=======================新增活动======================================

var submitPromotionButton={text:"添加", handler:function(){this.submit()}};
var cancelPromotionButton={text:"取消", handler:function(){this.cancel()}, isDefault:true};

var onNewPromotionSuccess=function(o) {
	//获取返回的活动对象(promotion)
	var json=JSON.parse(o.responseText);
	
	alert(o.responseText);
	
	//替换全局变量promotion
	promotion=json.promotion;
	
	//刷新活动（管理）清单列表
	
	//刷新base区域，并清空其它区域
	showPromotion();
};

var onNewPromotionFailure=function(o) {
};

var newPromotionDialog=new Dialog('newPromotionDialog', 
								{width:"400px",
								fixedcenter:true,
								modal:true,
								buttons : [submitPromotionButton, cancelPromotionButton]
								}
);

var onNewPromotionButtonClick=function(){
	newPromotionDialog.setHeader('新增活动');
	newPromotionDialog.callback={success:onNewPromotionSuccess, failure:onNewPromotionFailure};
	newPromotionDialog.render();
	newPromotionDialog.show();
};

Event.on('newPromotionButton', 'click', onNewPromotionButtonClick);



/**
 * 显示活动
 * @param {} o
 */
var showPromotion=function() {
	element('promotionName').innerText=promotion.title;
	element('promotionId').innerText=promotion.id;
	element('promotionDuration').innerText=promotion.startDate+'——'+promotion.endDate;
	element('promotionContent').innerText=promotion.desc;
	element('promotion').style.display="block";
	
	loadAttachment();
};



/**
 * 从服务器获取promotion, 并显示
 * @param {} id
 */
var loadPromotion=function(id){
	var callback = {
		cache : false,
		success : function(o) {
			promotion=JSON.parse(o.responseText).promotion;
			showPromotion();
		}
		}
	Connect.asyncRequest('GET', '/promotion/'+id, callback);
};



/**
 * 在左侧导航区显示营销活动清单
 * @return
 */
var showPromotionList = function() {	
	var callback = {
		cache : false,
		success : function(o) {
			var list=[];
			list = JSON.parse(o.responseText);
			var html='<ul>';
			for (var i = 0, len = list.length; i < len; ++i) {
				html=html+'<li><a href="#" onclick="loadPromotion('+list[i].id+')">'+list[i].title+'</a></li>';
			}
			html=html+'</ul>';
			var promotionListModule;
			if (!promotionListModule) {
				promotionListModule = new YAHOO.widget.Module("promotionListModule", { visible: false });
			}
			
			promotionListModule.setHeader("营销活动");
			promotionListModule.setBody(html);
			promotionListModule.render("left");
			promotionListModule.show();		}
	}
	Connect.asyncRequest('GET', '/promotion/list', callback);
};

showPromotionList();



















